package cloudPayAdmin.admin.controller.traffic;

import cloudPayAdmin.admin.dbapp.entity.traffic.TToken;
import cloudPayAdmin.admin.dbapp.entity.traffic.TTrafficDetector;
import cloudPayAdmin.admin.entity.yingshiyun.YSYAccessTokenResp;
import cloudPayAdmin.admin.entity.yingshiyun.YSYBaseResp;
import cloudPayAdmin.admin.entity.yingshiyun.YSYDeviceCaptureResp;
import cloudPayAdmin.admin.service.traffic.TokenService;
import cloudPayAdmin.admin.service.traffic.TrafficDetectorService;
import cloudPayAdmin.constant.BusiError;
import cloudPayAdmin.util.AdminLteDataTableResp;
import cloudPayAdmin.util.HttpUtil;
import cloudPayAdmin.util.TimeUtil;
import com.alibaba.fastjson.JSON;
import com.jfinal.kit.HttpKit;
import com.project.m.api.common.biz.resp.BizResp;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//import showpic.Class1;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 展示用
 */
@Controller
@RequestMapping("/traffic/show")
public class ShowController {

	private final Logger logger = Logger.getLogger(getClass());

	@Autowired
	Environment env;

	@Autowired
	TrafficDetectorService trafficDetectorService;

	@Autowired
	TokenService tokenService;
	
	/**
	 * 跳转到选择摄像头页面
	 * @return
	 */
	@RequestMapping(value = "/toSelectDectorPage")
	public String toSelectDectorPage() {
		return "traffic/show/select-detector";
	}
	
	/**
	 * 获得所有Detector的数据
	 * @return
	 */
	@RequestMapping("/getAllDetectorData")
	@ResponseBody
	public String getAllDetectorData() {
		List<TTrafficDetector> detectorList = trafficDetectorService.findAll();
		return JSON.toJSONString(detectorList,AdminLteDataTableResp.filters);
	}
	
	@RequestMapping("/toDetectorVideoShowPage")
	public String toDetectorVideoShowPage(HttpServletRequest request,Long trafficDetectorId) {
		TTrafficDetector trafficDector = new TTrafficDetector();
		if(trafficDetectorId != null) {
			 trafficDector = trafficDetectorService.findById(trafficDetectorId);
		}
		
		request.setAttribute("trafficDector", trafficDector);
		return "traffic/show/detector-video-show";
	}

	@RequestMapping("/matlabTest")
	@ResponseBody
	public String matlabTest(HttpServletRequest request) {
		System.setProperty("java.awt.headless", "false");
		logger.info("matlabTest");
		BizResp resp = new BizResp();
		try {
			resp.setResult_code(BusiError.ERR_CODE_SUCCESS);


//			Class1 classTest = new Class1();
//			logger.info("classTest = " + JSON.toJSON(classTest));

//			int input = 1999;
//			Object[] resultList =  classTest.add(1, input);
//			//logger.info("resultList.length = " + resultList.length);
//			logger.info("result string = " + String.valueOf(resultList[0]));

//			Class1 classTest = new Class1();
//			logger.info("classTest = " + JSON.toJSON(classTest));
//
//			logger.info("classTest = " + JSON.toJSON(classTest));
//
//			File imageFile = new File("test.jpg");
//			logger.info("imageFile = " + JSON.toJSON(imageFile));
//
//			logger.info("url = " + env.getProperty("matlab.test.url"));
//			URL imageUrl = new URL("" + env.getProperty("matlab.test.url"));
//			logger.info("imageUrl = " + JSON.toJSON(imageUrl));
//
//			FileUtils.copyURLToFile(imageUrl, imageFile);
//			logger.info("imageFile = " + imageFile.getAbsolutePath());
//
//
//			//List imageInput = new ArrayList();
//			//imageInput.add(imageFile);
//			//List imageOutput = new ArrayList();
//
//			//logger.info("imageInput = " + JSON.toJSONString(imageInput));
//			Object[] resultList = classTest.showpic(imageFile.getAbsolutePath());   // classTest.work(1, imageFile.getAbsolutePath());
//			//classTest.work(imageInput, imageOutput);
//			logger.info("resultList = " + resultList.length);
//			//logger.info("imageOutput = " + JSON.toJSONString(imageOutput));
			System.setProperty("java.awt.headless", "true");
			return JSON.toJSONString(resp);
		} catch (Exception e) {
			e.printStackTrace();
			resp.setResult_code(BusiError.ERR_CODE_NET_INNER_POST);
			resp.setError_message(BusiError.ERR_MSG_NET_INNER_POST);
			return JSON.toJSONString(resp);
		}


	}

	@RequestMapping("/getScreenShot")
	@ResponseBody
	public String toGetSgcreenShot(HttpServletRequest request) {
		BizResp resp = new BizResp();
		try {
			String bodyString = HttpKit.readData(request);
			//logger.info("bodyString = " + bodyString);

			Map<String, Object> resultMap = JSON.toJavaObject(JSON.parseObject(bodyString), Map.class);
			//resultMap.get("trafficDetectorId");
			//System.out.println("parse = " + resultMap.get("trafficDetectorId"));
			Long trafficDetectorId = Long.parseLong(String.valueOf(resultMap.get("trafficDetectorId")));
			logger.info("trafficDetectorId = " + trafficDetectorId);

			TTrafficDetector trafficDetector = trafficDetectorService.findById(trafficDetectorId);
			if (trafficDetector == null) {
				resp.setResult_code(BusiError.ERR_CODE_DETECTOR_NONE);
				resp.setError_message(BusiError.ERR_MSG_DETECTOR_NONE);
				return JSON.toJSONString(resp);
			}

			//判断token是否过期
			List<TToken> tokenList = tokenService.findByTypeAndEnable(TToken.TYPE_YINGSHIYUN, true);
			TToken token = null;
			boolean whetherToGetToken = false;
			//判斷是否過期
			if (tokenList == null || tokenList.size() == 0) {
				whetherToGetToken = true;
			} else {
				token = tokenList.get(0);
				if (Long.valueOf(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR)) > Long.valueOf(token.getExpiresIn()).longValue() + Long.valueOf(token.getUpdateTime()).longValue()) {
					whetherToGetToken = true;
				}
			}
			logger.info("token = " + JSON.toJSONString(token));

			if (whetherToGetToken) {
				String tokenUrl = "https://open.ys7.com/api/lapp/token/get?appKey=" + env.getProperty("video.yingshiyun.appkey") + "&appSecret=" + env.getProperty("video.yingshiyun.secret");
				logger.info("tokenUrl = " + tokenUrl);

				String tokenResponse = HttpUtil.post(tokenUrl, "");
				//logger.info("tokenResponse = " + tokenResponse);

				YSYBaseResp tokenBaseResp = JSON.parseObject(tokenResponse, YSYBaseResp.class);
				//logger.info("code = " + tokenBaseResp.getCode());
				if (tokenBaseResp.getCode().equalsIgnoreCase(YSYBaseResp.YSY_RESPONSE_SUCCESS)) {

					YSYAccessTokenResp ysyAccessTokenResp = JSON.parseObject(JSON.toJSONString(tokenBaseResp.getData()), YSYAccessTokenResp.class);
					//logger.info("data = " + tokenBaseResp.getData());
					//logger.info("data json = " + JSON.toJSONString(tokenBaseResp.getData()));

					if (token == null) {
						token = new TToken();
						token.setType(TToken.TYPE_YINGSHIYUN);
						token.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
						token.setEnable(true);
					}
					token.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
					token.setToken(ysyAccessTokenResp.getAccessToken());
					token.setExpiresIn(ysyAccessTokenResp.getExpireTime());
					tokenService.saveToken(token);

				} else {
					resp.setResult_code(BusiError.ERR_CODE_INNER_GET_TOKEN_ERROR);
					resp.setError_message(BusiError.ERR_MSG_INNER_GET_TOKEN_ERROR + "" + tokenBaseResp.getMsg());
					return JSON.toJSONString(resp);
				}
			}

			//去获取截图
			String captureUrl = "https://open.ys7.com/api/lapp/device/capture?accessToken=" + token.getToken() + "&deviceSerial=" + trafficDetector.getDeviceSerial() + "&channelNo=1";
			logger.info("captureUrl = " + captureUrl);
			String captureResponse = HttpUtil.post(captureUrl, "");
			logger.info("captureResponse = " + captureResponse);
			YSYBaseResp captureBaseResp = JSON.parseObject(captureResponse, YSYBaseResp.class);
			if (captureBaseResp.getCode().equalsIgnoreCase(YSYBaseResp.YSY_RESPONSE_SUCCESS)) {
				YSYDeviceCaptureResp ysyDeviceCaptureResp = JSON.parseObject(JSON.toJSONString(captureBaseResp.getData()), YSYDeviceCaptureResp.class);
				logger.info("picUrl = " + ysyDeviceCaptureResp.getPicUrl());

				//FileUtils.copyURLToFile();


			} else {
				resp.setResult_code(BusiError.ERR_CODE_INNER_CAPTURE_ERROR);
				resp.setError_message(BusiError.ERR_MSG_INNER_CAPTURE_ERROR);
				return JSON.toJSONString(resp);
			}

			resp.setResult_code(BusiError.ERR_CODE_SUCCESS);
			resp.setError_message("");
			return JSON.toJSONString(resp);
		} catch (Exception e) {
			resp.setResult_code(BusiError.ERR_CODE_NET_INNER_POST);
			resp.setError_message(BusiError.ERR_MSG_NET_INNER_POST);
			return JSON.toJSONString(resp);
		}
	}


}
